﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zeus.Infra.Cache;
using Zeus.DataMongo.GameSdk.Repositories;
using Zeus.Domain.GameSdk.Model.Log;

namespace Zeus.Domain.GameSdk.Service.Log
{
    public class SdkLogService
    {
        private ILogRepository logRepository;
        private ICacheStorage cacheStorage;

        public SdkLogService(ILogRepository logRepository, ICacheStorage cacheStorage)
        {
            this.logRepository = logRepository;
            this.cacheStorage = cacheStorage;
        }

        public string AddRequestLog(string request)
        {
            string newId = Guid.NewGuid().ToString();
            
            SdkLog sdkLog = new SdkLog
            {
                ID = newId,
                Request = request,
                StartTime = DateTime.Now
            };

            logRepository.Add(sdkLog);

            return newId;
        }

        public void UpdateResponseLog(string logId, string response)
        {
            string storageKey = "sdklog_" + logId;
            SdkLog sdkLog = cacheStorage.Retrieve<SdkLog>(storageKey);

            if (sdkLog == null)
            {
                sdkLog = logRepository.QueryById(logId);
                cacheStorage.Store(storageKey, sdkLog);
            }

            sdkLog.Response = response;
            sdkLog.EndTime = DateTime.Now;

            logRepository.UpdateSingle(logId, sdkLog);
            cacheStorage.Store(storageKey, sdkLog);
        }
    }
}
